package org.example.user.warning.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.commons.constant.Constants;
import org.example.commons.controller.BaseController;
import org.example.commons.entity.SysFeedback;
import org.example.commons.entity.SysMessage;
import org.example.commons.entity.SysUser;
import org.example.commons.enums.ReadStatusEnum;
import org.example.commons.enums.SendToEnum;
import org.example.commons.utils.SortUtils;
import org.example.commons.vo.ResultVO;
import org.example.commons.websoket.MessageHandler;
import org.example.user.manage.service.ISysUserService;
import org.example.user.warning.form.UserMessageForm;
import org.example.user.warning.service.ISysMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bothin
 */
@RestController
@RequestMapping("/api/message")
public class SysMessageController extends BaseController {

    @Autowired
    private ISysMessageService messageService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private MessageHandler messageHandler;

    /**
     * 导出excel
     * @param response
     * @throws IOException
     */
    @GetMapping("/export/excel")
    public void exportExcel(@RequestParam(name = "ids", required = false)  Long[] ids,
                            @RequestParam(name = "isUnread", defaultValue = "false")  Boolean isUnread,
                            HttpServletResponse response) throws IOException {
        List<SysMessage> data = null;
        if (ids==null || ids.length==0){
            if (isUnread)
                data = messageService.findBackendByStatusMessage(ReadStatusEnum.NO.getCode());
            else
                data = messageService.findBackendByStatusMessage(ReadStatusEnum.YES.getCode());
//                data = messageService.findBackendMessage();

        }else {
            data = messageService.findByMessageIdIn(ids);
        }
        super.exportExcel(response,data, SysMessage.class,"消息数据表");
    }

    @GetMapping("/{id}")
    public ResultVO findOne(@PathVariable("id") Long id) {
        return ResultVO.success(messageService.queryById(id));
    }

    /**
     * 查询列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping
    public ResultVO findList(@RequestParam(name = "page", defaultValue = "1") Integer page,
                             @RequestParam(name = "size", defaultValue = "10") Integer size,
                             @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
                             @RequestParam(name = "field", defaultValue = "createTime") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysMessage> admins = messageService.queryAllPage(pageRequest);
        return ResultVO.success(admins);
    }

    /**
     * 查询列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping("/backend")
    public ResultVO findList2(@RequestParam(name = "page", defaultValue = "1") Integer page,
                             @RequestParam(name = "size", defaultValue = "10") Integer size,
                             @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
                             @RequestParam(name = "field", defaultValue = "createTime") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysMessage> admins = messageService.findBackendMessage(pageRequest);
        return ResultVO.success(admins);
    }

    /**
     * 查询列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping("/backend/read")
    public ResultVO findListRead(@RequestParam(name = "page", defaultValue = "1") Integer page,
                              @RequestParam(name = "size", defaultValue = "10") Integer size,
                              @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
                              @RequestParam(name = "field", defaultValue = "createTime") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysMessage> admins = messageService.findBackendMessage(ReadStatusEnum.YES.getCode(),pageRequest);
        return ResultVO.success(admins);
    }

    /**
     * 查询列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping("/backend/unread")
    public ResultVO findList3(@RequestParam(name = "page", defaultValue = "1") Integer page,
                              @RequestParam(name = "size", defaultValue = "10") Integer size,
                              @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
                              @RequestParam(name = "field", defaultValue = "createTime") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysMessage> admins = messageService.findBackendMessage(ReadStatusEnum.NO.getCode(),pageRequest);
        return ResultVO.success(admins);
    }

    /**
     * 查询某住户的消息列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping("/user")
    public ResultVO findUserMessageList(@RequestParam(name = "userId") Long userId,
                              @RequestParam(name = "page", defaultValue = "1") Integer page,
                              @RequestParam(name = "size", defaultValue = "10") Integer size,
                              @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
                              @RequestParam(name = "field", defaultValue = "createTime") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysMessage> messages = messageService.findUserMessage(userId,pageRequest);
        return ResultVO.success(messages);
    }

    /**
     * 查询列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping("/user/read")
    public ResultVO findList4(@RequestParam(name = "userId") Long userId,
                              @RequestParam(name = "page", defaultValue = "1") Integer page,
                              @RequestParam(name = "size", defaultValue = "10") Integer size,
                              @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
                              @RequestParam(name = "field", defaultValue = "createTime") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysMessage> messages = messageService.findUserMessage(userId,ReadStatusEnum.YES.getCode(),pageRequest);
        return ResultVO.success(messages);
    }

    /**
     * 查询列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping("/user/unread")
    public ResultVO findList5(@RequestParam(name = "userId") Long userId,
                              @RequestParam(name = "page", defaultValue = "1") Integer page,
                              @RequestParam(name = "size", defaultValue = "10") Integer size,
                              @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
                              @RequestParam(name = "field", defaultValue = "createTime") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysMessage> messages = messageService.findUserMessage(userId,ReadStatusEnum.YES.getCode(),pageRequest);
        return ResultVO.success(messages);
    }

    /**
     * 条件查询列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping("/search")
    public ResultVO searchList(@RequestParam(name = "userName", defaultValue = "") String name,
                               @RequestParam(name = "title", defaultValue = "")  String title,
                               @RequestParam(name = "dates", required = false) Date[] dates,
                               @RequestParam(name = "status", required = false) String status,
                               @RequestParam(name = "page", defaultValue = "1") Integer page,
                               @RequestParam(name = "size", defaultValue = "10") Integer size,
                               @RequestParam(name = "isAsc", defaultValue = "true") Boolean isAsc,
                               @RequestParam(name = "field", defaultValue = "") String field) {
        PageRequest pageRequest = null;
        if (StringUtils.isEmpty(field)) {
            pageRequest = PageRequest.of(page - 1, size);
        } else {
            //排序
            Sort sort = SortUtils.getSort(isAsc, field);
            pageRequest = PageRequest.of(page - 1, size, sort);
        }

        if (dates==null || dates.length<2){
            dates = new Date[2];
        }

        if (StringUtils.isEmpty(status))
            status = null;      //当status=null时查找所有

        Page<SysMessage> res = messageService.searchList(name, title, dates,status, pageRequest);
        return ResultVO.success(res);
    }

    /**
     * 更新或保存
     *
     * @param message 消息
     * @return ResultVO
     */
    @PostMapping
    public ResultVO saveSysAdmin(@RequestBody SysMessage message) {
        return ResultVO.success(messageService.insert(message));
    }

    /** 发送消息给用户 */
    @PostMapping("/send/user")
    @Transactional
    public ResultVO sendToUser(@RequestBody SysMessage message) throws IOException {
        if (message==null) return ResultVO.error();
        SysMessage backMessage = messageService.queryById(message.getMessageId());
        backMessage.setStatus(ReadStatusEnum.YES.getCode());        //设置为已读
        messageService.insert(backMessage);
        //发送消息给用户
        message.setMessageId(null);
        message.setStatus(ReadStatusEnum.NO.getCode());
        message.setSendTo(SendToEnum.USER.getCode());
        messageService.insert(message);
        //websocket发送消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type","message");
        map.put("data",message);
        messageHandler.sendMessage(message.getUserId(), Constants.MAPPER.writeValueAsString(map) );
        return ResultVO.success();
    }

    /** 发送消息给用户 */
    @PostMapping("/send/user/list")
    @Transactional
    public ResultVO sendToUserList(@RequestBody UserMessageForm message) throws IOException {
        if (message==null) return ResultVO.error();
        List<Long> userList = null;
        if (message.getIds().length == 0){
            userList = userService.queryAll().stream().map(SysUser::getUserId).collect(Collectors.toList());
        }else {
            userList = Arrays.asList(message.getIds());
        }

        for (Long uid : userList) {
            SysMessage sysMessage = new SysMessage();
            sysMessage.setUserName("住户");
            sysMessage.setTitle(message.getTitle());
            sysMessage.setContent(message.getContent());
            sysMessage.setStatus(ReadStatusEnum.NO.getCode());
            sysMessage.setSendTo(SendToEnum.USER.getCode());
            sysMessage.setUserId(uid);
            messageService.insert(sysMessage);
            //websocket发送消息
            HashMap<String, Object> map = new HashMap<>();
            map.put("type","message");
            map.put("data",message);
            messageHandler.sendMessage(uid, Constants.MAPPER.writeValueAsString(map) );
        }
        return ResultVO.success();
    }

    /** 更新消息为已读 */
    @PostMapping("/read")
    public ResultVO saveReadStatus(@RequestParam("messageId") Long id) {
        //设置为已读
        SysMessage message = messageService.updateReadStatus(id, ReadStatusEnum.YES.getCode());
        if (message==null) return ResultVO.error("消息状态更新错误！");
        return ResultVO.success(message);
    }

    @DeleteMapping
    public ResultVO delete(@RequestParam("id") Long id) {
        messageService.deleteById(id);
        return ResultVO.success();
    }

    @DeleteMapping("/list")
    @Transactional
    public ResultVO deleteList(@RequestParam("ids") Long[] ids) {
        for (Long id : ids) {
            messageService.deleteById(id);
        }
        return ResultVO.success();
    }

}
